package club.xiaojiawei.array;

import java.util.Arrays;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 4/30/22 11:31 PM
 * @question 顺时针打印矩阵
 * @description 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 */
public class SpiralOrder29 {

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};
        int[] result = spiralOrder(matrix);
        System.out.println(Arrays.toString(result));
    }

    /**
     * 按层模拟
     * @param matrix
     * @return
     */
    public static int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0){
            return new int[]{};
        }
        int t = 0, b = matrix.length - 1, l = 0, r = matrix[0].length - 1;
        int amount = (b + 1) * (r + 1);
        int[] result = new int[amount];
        int count = 0;
        while (true){
            if (count == amount){
                break;
            }
            for (int i = l; i <= r; i++){
                result[count++] = matrix[t][i];
            }
            if (count == amount){
                break;
            }
            t++;
            for (int i = t; i <= b; i++){
                result[count++] = matrix[i][r];
            }
            if (count == amount){
                break;
            }
            r--;
            for (int i = r; i >= l; i--){
                result[count++] = matrix[b][i];
            }
            if (count == amount){
                break;
            }
            b--;
            for (int i = b; i >= t; i--){
                result[count++] = matrix[i][l];
            }
            l++;
        }
        return result;
    }
}
